package com.xry.service.impl;

import com.xry.annotation.LogMethod;
import com.xry.bean.User;
import com.xry.mapper.UserDao;
import com.xry.service.UserService;
import com.xry.util.Page;
import com.xry.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Override
    @Cacheable(value = "user",key = "#p0")
    @LogMethod(serviceName = "增加用户信息")
    public User add(User user) {
        user.setPassword(PasswordUtil.getEncryption(user.getPassword()));
        //新增数据
        try {
            userDao.add(user);
            //通过主键查询数据库中的数据
            User result = userDao.one(user.getId());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("用户或邮箱已存在");
        }

    }

    @Override
    @CacheEvict(value = "user",key = "#p0")
    @LogMethod(serviceName = "删除用户信息")
    public int del(Integer id) {
        return userDao.del(id);
    }

    @Override
    @CachePut(value = "user",key = "#p0.id")
    @LogMethod(serviceName = "修改用户信息")
    public User edit(User user) {
        try{
            if(user.getPassword()!=null)
                user.setPassword(PasswordUtil.getEncryption(user.getPassword()));
            userDao.edit(user);
            User result=userDao.one(user.getId());
            return result;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("修改用户信息失败");
        }

    }

    @Override
//    @Cacheable(value = "user",key = "#p0")
    public List<User> all(User user) {
        return userDao.all( user);
    }

    @Cacheable(value = "user",key = "#p0")
    @Override
    public User one(Integer id) {
        return userDao.one(id);
    }

    @Override
//    @Cacheable(value = "user",key = "#p0")
    public void page(Page page,User user){
        int count=userDao.pageCount(user);
        Object data=userDao.page(page,user);
        page.setCount(count);
        page.setData(data);
    }

    @Override
    public Map<String, Integer> countGender() {
        return userDao.countGender();
    }

}
